package test;

/**
 * @author WYC
 * @version 1.0
 * @ClassName CommandExample
 * @date 2024/12/14 0:58
 * @description
 */
// 命令接口
interface Command {
    void execute();
}

// 具体命令 - 开灯命令
class LightOnCommand implements Command {
    private Light light;

    public LightOnCommand(Light light) {
        this.light = light;
    }

    public void execute() {
        light.turnOn();
    }
}

// 具体命令 - 关灯命令
class LightOffCommand implements Command {
    private Light light;

    public LightOffCommand(Light light) {
        this.light = light;
    }

    public void execute() {
        light.turnOff();
    }
}

// 接收者 - Light
class Light {
    public void turnOn() {
        System.out.println("灯开了");
    }

    public void turnOff() {
        System.out.println("灯关了");
    }
}

// 请求者 - 控制器
class RemoteControl {
    private Command command;

    public void setCommand(Command command) {
        this.command = command;
    }

    public void pressButton() {
        command.execute();
    }
}

public class CommandExample {
    public static void main(String[] args) {
        Light light = new Light();

        // 创建命令对象
        Command lightOn = new LightOnCommand(light);
        Command lightOff = new LightOffCommand(light);

        // 创建控制器并设置命令
        RemoteControl remote = new RemoteControl();

        remote.setCommand(lightOn);
        remote.pressButton(); // 输出 "灯开了"

        remote.setCommand(lightOff);
        remote.pressButton(); // 输出 "灯关了"
    }
}
